<?php
/**
 * Created by PhpStorm.
 * User: 李京蔚
 * Date: 2018/7/10
 * Time: 13:58
 */

namespace App\Http\Controllers\Users;

use App\Models\AccountApi;
use App\Models\User;
use App\Models\UserLogin;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class LoginController extends ApiController
{
    use AuthenticatesUsers;

    /**
     * 功能：用户登录
     * @param Request $request
     * @param *string:device#设备号
     * @param *string:device_type#设备类型：0-PC，1-Web，2-IOS，3-Android
     * @param *string:mobile#手机号
     * @param *string:password#密码（MD5加密转大写）
     * @return mixed
     */
    public function login(Request $request)
    {
        $input = $request->all();
        $result = Validator::make($input, [
            'device' => 'required',
            'device_type' => 'required|in:0,1,2,3',
            'mobile' => 'required|regex:/^1[3456789]\d{9}$/',
            'password' => 'required|',
        ], [
            'device.required' => '缺少设备号！',
            'device_type.required' => '缺少设备类型！',
            'device_type.in' => '设备类型只能（PC、Web、IOS、Android）！',
            'mobile.required' => '请输入手机号！',
            'mobile.regex' => '手机号格式错误！',
            'password.required' => '请输入密码！',
        ]);
        if ($result->fails()) {
            return $this->setStatusCode(412)->message($result->errors()->first());
        }
        $device = $input['device'];
        $device_type = $input['device_type'];
        $expiry_time = time() + (3600 * 24 * 7);
        unset($input['device']);
        unset($input['device_type']);
        $user = User::where('mobile', $input['mobile'])->first();
        if ($user) {
            if (!password_verify($input['password'], $user->password)) {
                return $this->setStatusCode(412)->message('账号或密码错误！');
            }
            if ($user->is_disable == 1) {
                return $this->setStatusCode(412)->message('账号已被冻结，请联系客服！');
            }
            if ($user->is_blacklist == 1) {
                return $this->setStatusCode(412)->message('账号已被拉黑,请联系客服！');
            }
            if ($user->status == 1) {
                return $this->setStatusCode(412)->message('账号异常！');
            }
            //生成token
            $token = md5(sprintf("%s-%s-%s", uniqid('login_', true), $user->user_id, $device));
            //IP
            $ip = $request->getClientIp();
            try {
                DB::beginTransaction();
                //记录最后登录信息
                $update_user = User::where('user_id', $user->user_id)->update([
                    'last_login_ip' => $ip,
                    'last_login_time' => date('Y-m-d H:i:s', time()),
                ]);
                if ($update_user === false) {
                    throw new \Exception('登录出错！');
                }
                //验证是否APP
                if ($device_type > 1) {
                    $re = AccountApi::where([['user_id' => $user->user_id], ['device_type', '>', 1]])->update(['status' => 1]);
                    if ($re === false) {
                        throw new \Exception('修改出错！');
                    }
                }
                //添加token记录
                $res = AccountApi::insert([
                    'user_id' => $user->user_id,
                    'device' => $device,
                    'device_type' => $device_type,
                    'token' => $token,
                    'expires_time' => $expiry_time,
                ]);
                if ($res === false) {
                    throw new \Exception('保存数据出错！');
                }
                //登录记录
                if ($ip != '127.0.0.1') {
                    $ipAddress = getIpLookup($ip);
                    $login_ip_address = is_array($ipAddress) ? $ipAddress['country'] . $ipAddress['region'] . $ipAddress['city'] . $ipAddress['isp'] : '';
                }else{
                    $login_ip_address = '内部网IP';
                }
                $login_list = UserLogin::insert([
                    'user_id' => $user->user_id,
                    'login_ip' => $ip,
                    'login_ip_address' => $login_ip_address,
                    'device_type' => $device_type,
                ]);
                if ($login_list === false) {
                    throw new \Exception('添加记录出错！');
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollback();//事务回滚
                return $this->setStatusCode(412)->message($e->getMessage());
            }
            $data = [
                'device' => $device,
                'token' => $token,
                'expires_time' => $expiry_time,
            ];
            return $this->success($data);
        }
        return $this->setStatusCode(412)->message('手机号或密码错误！');
    }
}